<template>
  <div style="position: absolute; top: 40%; left: 0px; width: 45%">
    <el-form ref="ruleFormRef" :model="ruleForm" label-width="auto" style="max-width: 600px; margin: 0 auto"
      :size="formSize" :rules="rules">
      <el-form-item label="姓名" prop="name" v-if="!isLoginMode">
        <el-input v-model="ruleForm.name" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email" :rules="[
        {
          required: true,
          message: 'Please input email address',
          trigger: 'blur',
        },
        {
          type: 'email',
          message: 'Please input correct email address',
          trigger: ['blur', 'change'],
        },
      ]">
        <el-input v-model="ruleForm.email"> </el-input>
      </el-form-item>

      <el-form-item label="密码" prop="pass">
        <el-input v-model="ruleForm.pass" type="password" placeholder="Please input password" autocomplete="off"
          show-password />
      </el-form-item>

      <el-form-item>
        <el-checkbox v-model="ruleForm.type" name="type">
          {{ isLoginMode ? "记住我" : "我同意该条款" }}
        </el-checkbox>
      </el-form-item>

      <el-form-item>
        <button @click="handleLogin">
          {{ isLoginMode ? "登录" : "注册" }}
        </button>
      </el-form-item>

      <el-form-item>
        <div class="linkToRegister">
          <button @click="toggleMode">
            {{ isLoginMode ? "没有账号? 点击注册" : "已有账号?点击登录" }}
          </button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive } from "vue";
import { ref } from "vue";
import {
  ComponentSize,
  FormInstance,
  FormRules,
  ElMessage,
} from "element-plus";
import { useRouter } from "vue-router";

// 定义用户名和密码的响应式数据
const router = useRouter();

let isLoginMode = ref(true);
const emit = defineEmits(["sendData"]);

// 定义 toggleMode 方法，使用类型注解明确参数类型
const toggleMode = (event: MouseEvent) => {
  // 阻止按钮的默认提交行为
  event.preventDefault();
  isLoginMode.value = !isLoginMode.value;
  console.log(isLoginMode.value);

  emit("sendData", isLoginMode.value);
};

interface RuleForm {
  name: string;
  pass: string;
  type: boolean;
  email: string;
}

const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  name: "Hello",
  pass: "",
  type: false,
  email: "",
});

const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: "Please input name", trigger: "blur" },
    { min: 3, message: "Length greater than 3", trigger: "blur" },
  ],
  pass: [
    { required: true, message: "Please input password", trigger: "blur" },
    { min: 6, message: "Length greater than 6", trigger: "blur" },
  ],
});

// 定义登录处理函数
const handleLogin = async (event: MouseEvent) => {
  if (isLoginMode.value) {
    // 处理登录逻辑
    console.log("用户点击了登录按钮");

    if (ruleForm.type) {
      console.log("用户选择记住我");
      // 这里可以添加记住我相关的逻辑，如存储用户信息到本地存储等
    }

    try {
      // 从 localStorage 中获取数据，键为 'userData'
      const storedData = localStorage.getItem("userData");
      if (storedData) {
        // 将存储的 JSON 字符串解析为对象
        let userData = JSON.parse(storedData);
        console.log("从 localStorage 中获取的数据:", userData);

        // 输入框与localstorage的值进行对比，相同则跳转。
        if (
          ruleForm.email === userData.email &&
          ruleForm.pass === userData.password
        ) {
          // 使用router.push进行页面跳转，跳转到名为'Home'的路由（对应首页）
          await router.push({ name: "index" });
          console.log("route.push running!");
        } else {
          alert("邮箱或密码错误");
        }
      } else {
        console.log("未找到存储的数据");
      }
    } catch (error) {
      console.error("从 localStorage 获取数据时出错: ", error);
    }
  } else {
    // 处理注册逻辑
    console.log("用户点击了注册按钮");

    ruleFormRef.value?.validate((valid) => {
      if (valid) {
        if (ruleForm.type) {
          console.log("用户同意该条款");
        } else {
          ElMessage.error("请勾选我同意该条款");
          // 阻止按钮的默认提交行为
          event.preventDefault();
          return;
        }

        ElMessage.success("提交成功");

        // 存储数据到 localStorage
        const data = {
          name: ruleForm.name,
          email: ruleForm.email,
          password: ruleForm.pass,
        };
        try {
          // 将数据转换为 JSON 字符串
          const jsonData = JSON.stringify(data);
          // 存储数据，使用 'userData' 作为键
          localStorage.setItem("userData", jsonData);
          console.log("数据已成功存储到 localStorage");
        } catch (error) {
          console.error("存储数据到 localStorage 时出错: ", error);
        }
      } else {
        ElMessage.error("请完善表单信息");
        // 阻止按钮的默认提交行为
        event.preventDefault();
      }
    });
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.linkToRegister {
  margin: 0 auto;
}

.linkToRegister button {
  background-color: #fff;
  color: black;
  border-style: none;
  cursor: pointer;
}

button {
  width: 100%;
  height: 40px;
  background-color: rgb(82.4, 155.2, 46.4);
  color: #fff;
  border-style: none;
  cursor: pointer;
}
</style>